/*
 * Copyright 2011 myTDev.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.mytdev.util.concurrent;

import java.util.Map;
import java.util.HashMap;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;
import java.util.logging.Level;

/**
 * A class allowing to post events (Runnable) to be executed on a specific 
 * thread.
 */
public final class ExecutionThread extends Thread {

    /** Logger. */
    private static final Logger LOG = Logger.getLogger(ExecutionThread.class.getName());
    
    /** Poll event timeout default value in milliseconds. */
    private static final long DEFAULT_POLL_TIMEOUT = 500L;
    
    /** The ExecutionThread instances. */
    private static final Map<String, ExecutionThread> THREADS = new HashMap<String, ExecutionThread>();

    /** This thread events queue. */
    private final BlockingQueue<Runnable> eventsQueue = new LinkedBlockingQueue<Runnable>();
    
    /** Poll event timeout in milliseconds. */
    private long pollTimeout = DEFAULT_POLL_TIMEOUT;
    
    /**  */
    private boolean doRun = true;
    
    /**
     * Private constructor to prevent creation from outside.
     */
    private ExecutionThread(String threadName) {
        super(threadName);
    }
    
    /**
     * Creates then returns an ExecutionThread with the specified name.
     * @param threadName the thread to create name.
     * @return an ExecutionThread instance.
     * @throws IllegalArgumentException if an ExecutionThread with the 
     * specified name already exists.
     */
    public static synchronized ExecutionThread create(String threadName) {
        if(THREADS.get(threadName) != null) {
            throw new IllegalArgumentException("ExecutionThread already exists: " + threadName);
        }
        ExecutionThread thread = new ExecutionThread(threadName);
        THREADS.put(threadName, thread);
        return thread;
    }
    
    /**
     * Returns the ExecutionThread with the specified name.
     * @param threadName the ExecutionThread name.
     * @return an ExecutionThread instance or null if no ExecutionThread with 
     * the specified name exists.
     */
    public static ExecutionThread get(String threadName) {
        return THREADS.get(threadName);
    }
    
    /**
     * Creates if necessary then returns the ExecutionThread with the 
     * specified name.
     * @param threadName the ExecutionThread name.
     * @return an ExecutionThread instance.
     */
    public static synchronized ExecutionThread getOrCreate(String threadName) {
        ExecutionThread thread = THREADS.get(threadName);
        if(thread == null) {
            thread = new ExecutionThread(threadName);
            THREADS.put(threadName, thread);
        }
        return thread;
    }
    
    /**
     * @deprecated this method should not be called from outside.
     */
    public void run() {
        while(doRun) {
            try {
                final Runnable runnable = eventsQueue.poll(pollTimeout, TimeUnit.MILLISECONDS );
                synchronized(runnable) {
                    runnable.run();
                    runnable.notifyAll();
                }
            } catch(InterruptedException ex) {
                LOG.log(Level.SEVERE, ex.getLocalizedMessage(), ex);
            }
        }
    }
    
    /**
     * Add the specified Runnable to this thread events queue then waits for 
     * this runnable to be run.
     * @param runnable the runnable to add to the events queue.
     * @throws InterruptedException if an InterruptedException occurs while 
     * waiting for the end of the runnable execution.
     */
    public void invokeAndWait(final Runnable runnable) throws InterruptedException {
        if(runnable == null) {
            throw new NullPointerException("runnable is null.");
        }
        synchronized(runnable) {
            eventsQueue.add(runnable);
            runnable.wait();
        }
    }
    
    /**
     * Add the specified Runnable to this thread events queue.
     * @param runnable the runnable to add to the events queue.
     */
    public void invokeLater(final Runnable runnable) {
        if(runnable == null) {
            throw new NullPointerException("runnable is null.");
        }
        eventsQueue.add(runnable);
    }
    
    /**
     * Returns this ExecutionThread poll timeout.
     * @return the poll timeout in milliseconds.
     */
    public long getPollTimeout() {
        return pollTimeout;
    }
    
    /**
     * Sets the poll timeout.
     * @param pollTimeout the pollTimeout in milliseconds.
     */
    public void setPollTimeout(long pollTimeout) {
        this.pollTimeout = pollTimeout;
    }
    
    /**
     * Asserts if this ExecutionThread is the current thread.
     * @throws IllegalArgumentException if this ExecutionThread is not the 
     * current thread. 
     */
    public void assertCurrentThread() {
        assertCurrentThread(this);
    }
    
    /**
     * Asserts if the ExecutionThread which the name is specified is the 
     * current thread.
     * @param threadName the expected current thread name. It must be the name of 
     * an ExecutionThread created with the ExecutionThread#create(String) 
     * method.
     * @throws IllegalArgumentException if the specified thread is not the 
     * current thread. 
     */
    public static void assertCurrentThread(String threadName) {
        assertCurrentThread(THREADS.get(threadName));
    }
    
    /**
     * Asserts if the specified thread is the current thread.
     * @param thread the expected current thread.
     * @throws IllegalArgumentException if the specified thread is not the 
     * current thread. 
     */
    public static void assertCurrentThread(Thread thread) {
        Thread currentThread = Thread.currentThread();
        if(! currentThread.equals(thread)) {
            StringBuilder message = new StringBuilder("invalid current thread, expected: ");
            message.append(thread).append(" current: ").append(currentThread);
            throw new IllegalArgumentException(message.toString());
        }
    }
    
    /**
     * Returns true if this ExecutionThread is the current thread.
     * @return true if this ExecutionThread is the current thread.
     */
    public boolean isCurrentThread() {
        return isCurrentThread(this);
    }
    
    /**
     * Returns true if the ExecutionThread which the name is specified is the 
     * current thread.
     * @param threadName the expected current thread name. It must be the name of 
     * an ExecutionThread created with the ExecutionThread#create(String) 
     * method.
     * @return true if the ExecutionThread which the name is specified is the 
     * current thread.
     */
    public static boolean isCurrentThread(String threadName) {
        return isCurrentThread(THREADS.get(threadName));
    }
    
    /**
     * Returns true if the specified thread is the current thread.
     * @param thread the expected current thread.
     * @return true if the specified thread is the current thread, false otherwise.
     */
    public static boolean isCurrentThread(Thread thread) {
        return Thread.currentThread().equals(thread);
    }
}